package com.zsrd.system.controller;


import ch.qos.logback.classic.util.LogbackMDCAdapter;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zsrd.auth.core.UserInfoUtil;
import com.zsrd.core.response.ResponseSupport;
import com.zsrd.system.domain.SysUser;
import com.zsrd.system.domain.SysUserRole;
import com.zsrd.system.service.SysUserRoleService;
import com.zsrd.system.service.SysUserService;
import com.zsrd.system.util.RandomPassword;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Xxx
 * @since 2023-11-22
 */
@RestController
@RequestMapping("/sysUser")
@Api(value="用户列表",tags="用户列表")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;
    /**
     * 分页
     * @param
     * @return
     */

    @RequestMapping(value = "list",method = RequestMethod.POST)
    @ApiOperation(value = "用户列表",notes = "用户列表")
    public ResponseSupport list(@RequestBody SysUser sysUser){

            IPage<SysUser> pbPublicityIPage = sysUserService.list(sysUser);
            return ResponseSupport.success(pbPublicityIPage);
    }

    /**
     * 查看
     * @param
     * @return
     */
    @RequestMapping(value = "getById",method = RequestMethod.POST)
    @ApiOperation(value = "查看",notes = "查看")
    public ResponseSupport getById(@RequestBody SysUser sysUser){
        SysUser byId = sysUserService.getById(sysUser);
            return ResponseSupport.success(byId);
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ApiOperation(value = "删除",notes = "删除")
    public ResponseSupport delete(@RequestBody SysUser sysUser){

        List<String> list = Arrays.asList("admin", "manager");
        List<String> roleList = UserInfoUtil.getUserRole();
        if (roleList.containsAll(list)){
            sysUserService.removeById(sysUser.getUserId());
            sysUserRoleService.removeById(sysUser.getUserId());
            return  ResponseSupport.success("删除成功");
        }
        sysUser.setDelFlag(2);
        boolean b = sysUserService.updateById(sysUser);
        if (b==false){
            return ResponseSupport.fail("删除失败");
        }
        return ResponseSupport.success(b);
    }


    @RequestMapping(value = "randomPassword",method = RequestMethod.POST)
    @ApiOperation(value = "随机密码生成",notes = "随机密码生成")
    public ResponseSupport randomPassword(@RequestBody SysUser sysUser){

        String s = SecureUtil.sha256(sysUser.getPassword());
        sysUser.setPassword(s);
        if (StringUtils.isEmpty(sysUser.getPassword())){
            return ResponseSupport.fail("密码生成为空");
        }
        boolean b = sysUserService.updateById(sysUser);
        if (b==false){
            return ResponseSupport.fail("修改失败");
        }
        StpUtil.logout(sysUser.getUserId());
        return ResponseSupport.success("修改密码成功,请重新登录");
    }





    @Transactional
    @RequestMapping(value = "update",method = RequestMethod.POST)
    @ApiOperation(value = "修改",notes = "修改")
    public ResponseSupport update(@RequestBody SysUser sysUser) {

        List<SysUserRole> list = new ArrayList<>();
        if (sysUser.getUserId() == null) {
            //为了获取数据库里面有没有重复的名字
            SysUser byUsername = sysUserService.getByUsername(sysUser.getUsername());
            if (byUsername!=null){
                return ResponseSupport.fail("用户名重复");
            }
            String password = SecureUtil.sha256(sysUser.getPassword());
            sysUser.setPassword(password);
            sysUser.setDelFlag(0);
            sysUser.setCreateTime(new Date());
            sysUser.setUpdateTime(new Date());
            sysUser.setStatus(1);
             sysUserService.save(sysUser);

             //为了获取用户的id
            SysUser user = sysUserService.getByUsername(sysUser.getUsername());
            Long userId = user.getUserId();
            String data = sysUser.getData();
            String substring = data.substring(0, data.length() - 0);
            String[] split = substring.split(",");

            for (String s : split) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(Math.toIntExact(userId));
                sysUserRole.setRoleId((int) Long.valueOf(s).longValue());
                list.add(sysUserRole);
            }
            sysUserRoleService.saveBatch(list);
        } else {
            if (!StringUtils.isEmpty(sysUser.getData())) {
                LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(SysUserRole::getUserId, sysUser.getUserId());
                sysUserRoleService.remove(lambdaQueryWrapper);

                String data = sysUser.getData();
                String substring = data.substring(0, data.length() - 0);
                String[] split = substring.split(",");

                for (String s : split) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(Math.toIntExact(sysUser.getUserId()));
                    sysUserRole.setRoleId((int) Long.valueOf(s).longValue());
                    list.add(sysUserRole);
                }
                sysUserRoleService.saveBatch(list);
            }


            sysUser.setUpdateTime(new Date());
            sysUserService.saveOrUpdate(sysUser);
        }
        return ResponseSupport.success();

    }




}

